from django.http import Http404
from django.shortcuts import render

# Create your views here.

# GET /areas/
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView, ListAPIView,RetrieveAPIView
from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework_extensions.cache.mixins import CacheResponseMixin

from areas.models import Area
from areas.serializers import AreaSerializers, SubAreaSerializer
from rest_framework.pagination import PageNumberPagination


class AreasView(ListAPIView):


    '''
    获取省级地区
    '''
    serializer_class = AreaSerializers
    queryset = Area.objects.filter(parent=None)

    # def get(self, request):
    #     '''
    #     1. 获取省份信息
    #     2. 序列化返回
    #     '''
    #     # 1. 获取省份信息
    #     areas = self.get_queryset()
    #     # 2. 序列化返回
    #     serializer = self.get_serializer(areas, many=True)
    #     return Response(serializer.data)
    #


# GET /areas/(?P<pk>\d)/
# 获取指定地区信息
class SubAreasView(RetrieveAPIView):
    serializer_class = SubAreaSerializer
    queryset = Area.objects.all()
    # def get(self, request, pk):
    #     '''
    #     获取指定地区信息
    #     1. 获取PK指定地区信息
    #     2. 序列化返回
    #     '''
    #
    #     # 1.获取PK指定地区信息
    #     try:
    #         area = self.get_object()
    #     except Area.DoesNotExist:
    #         raise Http404
    #
    #     # 2.序列化返回
    #     serializer = self.get_serializer(area)
    #
    #     return Response(serializer.data)
    #



class AreaViewSet(CacheResponseMixin,ReadOnlyModelViewSet):
    # 关闭分页
    pagination_class = None
    '''地区视图集'''
    def get_serializer_class(self):
        if self.action == 'list':
            return AreaSerializers
        else:
            return SubAreaSerializer

    def get_queryset(self):
        if self.action == 'list':
            return Area.objects.filter(parent=None)
        else:
            return Area.objects.all()

